<template>
  <div class="WorkingSchedule" v-loading="loading">
    <el-form ref="form" :model="form" label-position="top" class="myform">
      <div>
        <el-form-item label="工厂" class="myform-item">
          <el-input
            v-model="form.factory_name"
            placeholder="请输入工厂名称"
            size="mini"
          ></el-input>
          <!-- <el-select
            v-model="form.supplier_id"
            placeholder="请选择"
            clearable
            @keyup.enter.native="onSearch"
          >
            <el-option
              v-for="item in factoryList"
              :key="item.supplier_id"
              :label="item.factory_name"
              :value="item.supplier_id"
            >
            </el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item label="SKU" class="myform-item">
          <el-input
            v-model="form.sku_code"
            placeholder="请输入SKU"
            size="mini"
          ></el-input>
        </el-form-item>
        <el-form-item label="审批状态:" class="myform-item">
          <el-select v-model="form.status" placeholder="请选择" clearable>
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="margin-top: 50px" class="myform-item">
          <el-button type="primary" @click="onSearch">查询</el-button>
        </el-form-item>
      </div>
      <div>
        <el-form-item style="margin-top: 50px" class="myform-item">
          <el-button type="primary" @click="onPay">新建</el-button>
        </el-form-item>
        <el-form-item style="margin-top: 50px">
          <el-button @click="onStamp">打印</el-button>
        </el-form-item>
      </div>
    </el-form>
    <el-table
      class="table_header"
      header-cell-class-name="all-select"
      :data="tableData"
      style="width: 100%"
      border
      @selection-change="handleSelectionChangeA"
    >
      <el-table-column type="selection" width="55" :selectable="selectable">
      </el-table-column>
      <el-table-column label="审批id" align="center" prop="instance_code">
      </el-table-column>
      <el-table-column label="所属工厂" align="center" prop="factory_name">
      </el-table-column>
      <!-- <el-table-column label="箱单号" align="center" prop="dispatch_number">
      </el-table-column> -->
      <!-- <el-table-column
        label="所属发货单号"
        align="center"
        prop="invoice_number"
      >
      </el-table-column> -->
      <el-table-column label="退货SKU" align="center" prop="sku_codearr">
        <template slot-scope="{ row }">
          <div v-for="(item, index) in row.sku_codearr" :key="index">
            {{ item.sku_code }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="退货总数量" align="center" prop="num">
      </el-table-column>
      <el-table-column label="退货原因" align="center" prop="reason">
      </el-table-column>
      <el-table-column label="图片" align="center" prop="pay_images">
        <template slot-scope="{ row }">
          <div v-if="row.images" style="display: flex">
            <el-image
              v-for="item in row.images"
              :key="item"
              :src="item"
              fit="contain"
              :lazy="true"
              :preview-src-list="row.images"
              style="width: 100px; height: 100px"
            ></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createtime">
      </el-table-column>
      <el-table-column label="审批状态" align="center" prop="status">
        <template slot-scope="{ row }">
          <div
            :style="{
              color:
                row.status == 1
                  ? '#E6A23C'
                  : row.status == 2
                  ? '#67C23A'
                  : row.status == 3
                  ? 'red'
                  : '',
            }"
          >
            {{
              row.status == 0
                ? "未发起"
                : row.status == 1
                ? "审批中"
                : row.status == 2
                ? "已通过"
                : row.status == 3
                ? "已拒绝"
                : row.status == 4
                ? "已撤销"
                : ""
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="adduser">
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{ row }">
          <el-button type="text" @click="onContractReconciliationDetail(row.id)"
            >查看</el-button
          >
          <el-button type="text" @click="onEdit(row.id)" v-if="row.status == 0"
            >编辑</el-button
          >
          <el-button
            type="text"
            v-if="row.status == 0"
            style="color: red"
            @click="onDelete(row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-button
      type="primary"
      @click="onExamine"
      :disabled="!multipleSelectionA.length"
      style="margin-top: 10px"
      >发起审批</el-button
    >
    <pagination
      :form="form"
      :total="total"
      @paginationPostOrderTaskList="postWarehousegetdispatchretuenlist"
    />
    <!-- 审核 -->
    <el-dialog
      title="新建"
      :visible.sync="paydialogVisible"
      :lose-on-click-modal="false"
      :before-close="handleClose"
      width="1450px"
    >
      <div v-if="step == 1">
        <el-form ref="formC" class="myform" label-width="40px">
          <div>
            <el-form-item label="工厂" class="myform-item">
              <!-- <el-input
                v-model="factory_name"
                placeholder="请输入工厂名称"
                size="mini"
              ></el-input> -->
              <el-select
                v-model="factory_name"
                placeholder="请选择"
                clearable
                size="mini"
              >
                <el-option
                  v-for="item in factoryList"
                  :key="item.supplier_id"
                  :label="item.factory_name"
                  :value="item.factory_name"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form>
        <div>
          <el-form ref="formSku" class="myform" label-width="40px">
            <div>
              <el-form-item label="SKU" class="myform-item">
                <el-input
                  v-model="formSku.sku_code"
                  placeholder="请输入SKU"
                  size="mini"
                ></el-input>
              </el-form-item>
              <el-form-item label="数量" class="myform-item">
                <el-input
                  v-model="formSku.num"
                  placeholder="请输入数量"
                  type="number"
                  size="mini"
                ></el-input>
              </el-form-item>
              <el-form-item class="myform-item">
                <el-button
                  type="primary"
                  :disabled="!formSku.sku_code || !formSku.num"
                  @click="onAddSku"
                  size="mini"
                  >添加</el-button
                >
              </el-form-item>
            </div>
          </el-form>
        </div>
        <el-table :data="tableDataC" style="width: 100%" border size="mini">
          <el-table-column label="SKU" align="center" prop="sku_code">
          </el-table-column>
          <el-table-column label="数量" align="center" prop="num">
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="{ $index }">
              <el-button
                type="text"
                size="default"
                style="color: red"
                @click="onDeleteX($index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div>
          <div style="font-weight: 600; margin: 10px 0">退货原因（非必填）</div>
          <el-input
            v-model="reason"
            placeholder="请输入退货原因（非必填）"
            size="mini"
          ></el-input>
        </div>
        <div>
          <div style="font-weight: 600; margin: 10px 0">上传图片（非必填）</div>
          <el-upload
            action="https://ssy.13yu.com/index.php/Admin/Api/upload"
            list-type="picture-card"
            :on-success="handleSuccess"
            :before-remove="handleRemoves"
            :file-list="files"
            ref="uploadpay"
          >
            <i slot="default" class="el-icon-plus"></i>
          </el-upload>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button
          @click="onSubmit(0)"
          :disabled="!factory_name || !tableDataC.length"
          >提交数据</el-button
        >
        <el-button
          :loading="loading"
          :disabled="!factory_name || !tableDataC.length"
          type="primary"
          @click="onSubmit(1)"
          >发起审批</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="打印入库退货单"
      :visible.sync="paydialogVisibleD"
      :lose-on-click-modal="false"
      :before-close="handleClose"
      width="1450px"
    >
      <div>
        <el-form ref="formD" class="myform" label-width="40px">
          <div>
            <el-form-item label="工厂" class="myform-item">
              <el-input
                v-model="factory_name"
                placeholder="请输入工厂名称"
                size="mini"
              ></el-input>
            </el-form-item>
          </div>
          <div>
            <el-form-item class="myform-item">
              <el-button type="primary" @click="onSearchD" size="mini"
                >查询</el-button
              >
            </el-form-item>
          </div>
        </el-form>
        <div class="Transfers-list">
          <div class="Transfers-list-module">
            <div class="Transfers-list-module-search">
              <el-input
                v-model="dispatch_number"
                style="width: 400px"
                placeholder="请输入箱号"
                size="mini"
                @keyup.enter.native="onSearchD"
                clearable
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="onSearchD"
                ></el-button>
              </el-input>
            </div>
            <div class="Transfers-list-module-content myscroll">
              <el-table
                size="mini"
                :data="tableDataD"
                height="400"
                style="width: 100%"
                @selection-change="handleSelectionChangeD"
              >
                <el-table-column type="selection" width="55"> </el-table-column>
                <el-table-column prop="sku_codearr" label="退货SKU">
                  <template slot-scope="{ row }">
                    <div v-for="item in row.sku_codearr" :key="item.sku_code">
                      {{ item.sku_code }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="num" label="数量">
                  <template slot-scope="{ row }">
                    {{ row.num || 0 }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <div style="margin: 0 20px">
            <el-button
              type="primary"
              :disabled="!multipleSelectionD.length"
              @click="onAddD"
              >加入打印列表<i class="el-icon-arrow-right el-icon--right"></i
            ></el-button>
          </div>
          <div class="Transfers-list-module">
            <div class="Transfers-list-module-search">选中退货商品列表</div>
            <div class="Transfers-list-module-content myscroll">
              <el-table
                size="mini"
                :data="TableDataSelectD"
                height="400"
                style="width: 100%"
              >
                <el-table-column prop="sku_codearr" label="退货SKU">
                  <template slot-scope="{ row }">
                    <div v-for="item in row.sku_codearr" :key="item.sku_code">
                      {{ item.sku_code }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="num" label="数量">
                  <template slot-scope="{ row }">
                    {{ row.num || 0 }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                  <template slot-scope="{ $index }">
                    <el-button
                      type="text"
                      size="default"
                      style="color: red"
                      @click="onDeleteD($index)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button
          :loading="loading"
          type="primary"
          :disabled="!TableDataSelectD.length"
          @click="onAddStamp"
          >打 印</el-button
        >
      </span>
    </el-dialog>
    <div class="print">
      <stampPrint ref="print" />
    </div>
  </div>
</template>

<script>
import {
  postWarehousegetdispatchretuenlist,
  postWarehousegetdispatchlist,
  postWarehousegetdispatchlistsku,
  postWarehousesetdispatchretuenprintapprove,
  postWarehousegetdispatchretuenprintlist,
  postWarehousesetnodispatchlistsku,
  postWarehousegetdispatchretuendetail,
  postHomeCodeGetFactory,
  postWarehousesetinspectsku,
  postWarehousedeldispatchretuendetail,
} from "@/api";
import pagination from "@/components/pagination.vue";
import stampPrint from "./components/stampw.vue";
export default {
  components: { pagination, stampPrint },
  data() {
    return {
      qxobj: {},
      sid: "",
      loading: false,
      paydialogVisible: false,
      auditdialogVisible: false,
      paydialogVisibleD: false,
      factoryList: [],
      options: [
        {
          value: 0,
          label: "未发起",
        },
        {
          value: 1,
          label: "审批中",
        },
        {
          value: 2,
          label: "已通过",
        },
        {
          value: 3,
          label: "已拒绝",
        },
        {
          value: 4,
          label: "已撤销",
        },
      ],
      form: {
        factory_name: "",
        sku_code: "",
        number: "",
        status: 0,
        page: 1,
        size: 10,
        types: 2,
      },
      tableData: [],
      total: 1,
      step: 1,
      formC: {
        factory_name: "",
        page: 1,
        size: 10,
      },
      tableDataC: [],
      totalC: 1,
      tableDataX: [],
      TableDataSelect: [],
      rowX: "", //选中的箱单号
      sku_code: "",
      reason: "",
      factory_name: "",
      tableDataD: [],
      dispatch_number: "",
      TableDataSelectD: [],
      formSku: {
        sku_code: "",
        num: 1,
      },
      auditform: {
        status: 1,
      },
      // 审核
      ExtraAudit: {
        id: "",
        status: 1,
      },
      multipleSelection: [],
      multipleSelectionA: [],
      multipleSelectionD: [],
    };
  },
  activated() {
    // this.qxobj = JSON.parse(this.$route.query.qxobj);
    let form = this.form;
    this.postHomeCodeGetFactory();
    this.postWarehousegetdispatchretuenlist(form);
  },
  methods: {
    handleRemoves(file) {
      let { files } = this;
      let index = files.findIndex((e) => e.url == file.url);
      files.splice(index, 1);
      this.files = files;
      return true;
    },
    handleSuccess(response) {
      let { files } = this;
      let obj = {
        name: "图片",
        url: response.img,
      };
      files.push(obj);
      this.files = files;
    },
    selectable: function (row, index) {
      // 地址不是 "秦皇岛市海港区居民" 才能被选中
      if (!row.instance_code) {
        return true;
      }
    },
    async onAddSku() {
      let { formSku, tableDataC } = this;
      let istrue = tableDataC.some(
        (value, index) => formSku.sku_code == value.sku_code
      );
      if (istrue) {
        return this.$message.warning("sku已存在");
      }
      let obj = {
        sku_code: formSku.sku_code,
      };
      let res = await postWarehousesetinspectsku(obj);
      tableDataC.push(formSku);
      this.tableDataC = tableDataC;
      this.formSku = {
        sku_code: "",
        num: 1,
      };
    },
    onStamp() {
      this.factory_name = "";
      this.tableDataD = [];
      this.TableDataSelectD = [];
      this.sku_code = "";
      this.multipleSelectionD = [];
      this.paydialogVisibleD = true;
    },
    async onAddStamp() {
      let { TableDataSelectD } = this;
      let arr = [];
      for (let index = 0; index < TableDataSelectD.length; index++) {
        arr.push(TableDataSelectD[index].id);
      }
      this.$refs.print.print(arr);
      this.handleClose();
    },
    handleClose() {
      this.multipleSelection = [];
      this.tableDataX = [];
      this.TableDataSelect = [];
      this.sku_code = "";
      this.reason = "";
      this.step = 1;
      this.id = "";
      this.sid = "";
      this.rowX = "";
      this.factory_name = "";
      this.files = [];
      this.formC = {
        factory_name: "",
        page: 1,
        size: 10,
      };
      this.totalC = 1;
      this.tableDataC = [];
      this.paydialogVisible = false;
      this.paydialogVisibleD = false;
    },
    onStep(e) {
      if (e == 1) {
        this.multipleSelection = [];
        this.tableDataX = [];
        this.TableDataSelect = [];
        this.sku_code = "";
        this.reason = "";
      }

      this.step = e;
    },
    async onInput(e, index, num) {
      let { TableDataSelect } = this;
      let tmpObj = TableDataSelect[index];
      if (Number(e) && Number(e) <= num) {
        tmpObj.number = e;
      } else {
        tmpObj.number = 1;
      }
      this.$set(this.TableDataSelect, index, tmpObj);
    },
    async onSubmit(is_approve) {
      let { sid, tableDataC, reason, factory_name, form, files } = this;
      this.loading = true;
      let images = [];
      if (files && files.length) {
        files.forEach((e) => {
          images.push(e.url);
        });
      }

      let obj = {
        factory_name,
        sku_codearr: tableDataC,
        reason,
        images,
        is_approve,
      };
      console.log("sid", sid);
      if (sid) {
        obj.id = sid;
      }
      try {
        await postWarehousesetnodispatchlistsku(obj);
        this.postWarehousegetdispatchretuenlist(form);
        this.$message.success("成功");
        this.handleClose();
      } catch (error) {
        this.loading = false;
      }
    },
    onAdd() {
      let { multipleSelection, TableDataSelect } = this;
      multipleSelection = multipleSelection.map((e) => {
        e.number = 1;
        return e;
      });
      let arr = [];
      for (let index = 0; index < multipleSelection.length; index++) {
        let is = TableDataSelect.some((e) => {
          return (
            e.sku_code == multipleSelection[index].sku_code ||
            multipleSelection[index].num <= 0
          );
        });
        if (!is) {
          arr.push(multipleSelection[index]);
        }
      }
      TableDataSelect.push(...arr);
      this.TableDataSelect = TableDataSelect;
    },
    onAddD() {
      let { multipleSelectionD, TableDataSelectD } = this;
      let arr = [];
      for (let index = 0; index < multipleSelectionD.length; index++) {
        let is = TableDataSelectD.some((e) => {
          return e.sku_code == multipleSelectionD[index].sku_code;
        });
        if (!is) {
          arr.push(multipleSelectionD[index]);
        }
      }
      TableDataSelectD.push(...arr);
      this.TableDataSelectD = TableDataSelectD;
    },
    onPay(id) {
      this.id = id;
      this.formSku = {
        sku_code: "",
        num: 1,
      };
      this.tableDataC = [];
      this.factory_name = "";
      this.paydialogVisible = true;
    },
    // 审批进度
    onLookRun(id, type, run_id) {
      this.$router.push({ name: "contractrunid", query: { id, type, run_id } });
    },
    // 加工厂列表
    postHomeCodeGetFactory() {
      let obj = {
        type: 1,
        page: 1,
        size: 1000,
      };
      postHomeCodeGetFactory(obj).then((res) => {
        this.factoryList = res.data;
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSelectionChangeD(val) {
      this.multipleSelectionD = val;
    },

    handleSelectionChangeA(val) {
      this.multipleSelectionA = val;
    },
    // 审核
    async onExamine() {
      let { multipleSelectionA, form } = this;
      let ids = [];
      for (let index = 0; index < multipleSelectionA.length; index++) {
        ids.push(multipleSelectionA[index].id);
      }
      let obj = {
        ids,
        types: 2,
      };
      let res = await postWarehousesetdispatchretuenprintapprove(obj);
      this.multipleSelectionA = [];
      this.postWarehousegetdispatchretuenlist(form);
      this.$message.success("您已成功发起入库退货审批");
    },
    // 详情
    onContractReconciliationDetail(id) {
      this.$router.push({
        name: "CangrkthDetail",
        query: { id },
      });
    },
    onDeleteD(e) {
      let { TableDataSelectD } = this;
      this.$confirm("确定删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          TableDataSelectD.splice(e, 1);
          this.TableDataSelectD = TableDataSelectD;
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    onDeleteX(e) {
      let { tableDataC } = this;
      this.$confirm("确定删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          tableDataC.splice(e, 1);
          this.tableDataC = tableDataC;
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 删除
    onDelete(id) {
      this.loading = true;
      let form = this.form;
      let obj = {
        id,
      };
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          postWarehousedeldispatchretuendetail(obj).then((res) => {
            this.postWarehousegetdispatchretuenlist(form);
            this.$message({
              type: "success",
              message: "作废成功!",
            });
            this.loading = false;
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消作废",
          });
          this.loading = false;
        });
    },
    // 编辑
    async onEdit(id) {
      this.sid = id;
      let obj = {
        id,
      };
      let res = await postWarehousegetdispatchretuendetail(obj);
      let data = res.data;
      let sku_codearr = data.sku_codearr;
      this.tableDataC = sku_codearr;
      this.factory_name = data.factory_name;
      this.reason = data.reason;
      let images = data.images;
      let arr = [];
      this.paydialogVisible = true;
      if (images && images.length) {
        for (let index = 0; index < images.length; index++) {
          let obj = {
            name: "图片",
            url: images[index],
          };
          arr.push(obj);
        }
        this.files = arr;
      }
    },
    // 新建对账单
    onNewReconciliation() {
      this.$router.push({
        name: "ContractReconciliationFX",
        // query: { type: "addnew" },
      });
    },
    // 列表
    async postWarehousegetdispatchretuenlist(data) {
      this.loading = true;
      this.form = data;
      postWarehousegetdispatchretuenlist(data)
        .then((res) => {
          this.loading = false;
          console.log("采购列表", res);
          this.tableData = res.data;
          this.total = Number(res.total);
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    // SKU搜索
    async onSearchX() {
      let { sku_code, rowX } = this;
      let obj = {
        dispatch_number: rowX.dispatch_number,
        sku_code,
      };
      let res = await postWarehousegetdispatchlistsku(obj);
      this.tableDataX = res.data;
    },
    // 打印搜索
    async onSearchD() {
      let { factory_name, dispatch_number } = this;
      if (factory_name) {
        let obj = {
          factory_name,
          dispatch_number,
          types: 2,
        };
        let res = await postWarehousegetdispatchretuenprintlist(obj);
        this.tableDataD = res.data;
      }
    },
    // 搜索
    onSearch() {
      this.form.page = 1;
      this.form.size = 10;
      this.postWarehousegetdispatchretuenlist(this.form);
    },
    // 列表（创建）
    async postWarehousegetdispatchlist(data) {
      this.loading = true;
      this.formC = data;
      postWarehousegetdispatchlist(data)
        .then((res) => {
          this.loading = false;
          console.log("列表（创建）", res);
          this.tableDataC = res.data;
          this.totalC = Number(res.total);
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    // 搜索（创建）
    onSearchC() {
      this.formC.page = 1;
      this.formC.size = 10;
      this.postWarehousegetdispatchlist(this.formC);
    },
  },
};
</script>

<style lang="scss" scoped>
.print {
  position: fixed;
  top: 0;
  z-index: -100;
  visibility: hidden;
}
.table_header {
  //找到表头那一行，然后把里面的复选框隐藏掉

  /deep/ th .el-checkbox__inner {
    display: none !important;
  }
}
.Transfers-list {
  display: flex;
  align-items: center;

  .Transfers-list-module {
    border: 1px solid #efefef;
    width: 600px;
    border-radius: 4px;

    .Transfers-list-module-search {
      padding: 0 20px;
      height: 48px;
      display: flex;
      align-items: center;
      background-color: #f5f7fa;
      font-weight: 600;
      font-size: 12px;
    }

    .Transfers-list-module-content {
      height: 400px;

      /deep/ .el-table__row {
        height: 53px;
      }
    }
  }
}
.myform {
  display: flex;
  justify-content: space-between;
  > div {
    display: flex;
  }
  &-item {
    margin-right: 10px;
  }
}
.WorkingSchedule {
  background: #ffff;
  padding: 20px;
  border-radius: 2px;
  @include boxShadow;
}
</style>
